import IntersectionObserver from 'intersection-observer-polyfill'
import { useState, useEffect, MutableRefObject } from 'react';

window.IntersectionObserver = IntersectionObserver;

interface IAppear {
    /** dom是否展示 */
    isAppear: boolean;
    /** dom展示的百分比 */
    appearParsent: number;
}

/**
 * 监听dom的显示隐藏hooks
 * @param target dom的ref实例
 * @param showCallBack dom显示的回调函数
 * @param hideCallBack dom隐藏的回调函数
 */
export const useDomAppear = (target: MutableRefObject<any>, showCallBack?: () => void, hideCallBack?: () => void): IAppear => {
    const [state, setState] = useState<IAppear>({ isAppear: false, appearParsent: 0 });
    useEffect(() => {
        const io = new IntersectionObserver((entry) => {
            const { intersectionRatio } = entry[0];
            setState((prev) => {
                const isAppear = intersectionRatio > 0;
                if (prev.isAppear !== isAppear) {
                    if (isAppear) {
                        showCallBack?.()
                    } else {
                        hideCallBack?.()
                    }
                }
                return {
                    isAppear,
                    appearParsent: intersectionRatio
                }
            })
        })
        io.observe(target.current);
        return () => {
            io.unobserve(target.current)
        }
    }, [])
    return state;
}